package app.android.alampang.ui.core;

import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by Supanut on 2/18/2015.
 */
public class SwipeHandler extends GestureDetector.SimpleOnGestureListener implements View.OnTouchListener
{
    private final GestureDetector gestureDetector;

    private static final int SWIPE_THRESHOLD = 0;
    private static final int SWIPE_VELOCITY_THRESHOLD = 0;

    private OnSwipeTouchListener listener;
    public SwipeHandler(Context context){
        gestureDetector = new GestureDetector(context, this);
    }

    public void attachOnTouchListener(View view)
    {
        view.setOnTouchListener(this);
    }

    public void setOnSwipeTouchListener(OnSwipeTouchListener listener)
    {
        this.listener = listener;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (listener != null)
            listener.onSwipeMotion(v, event);

        return gestureDetector.onTouchEvent(event);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

        boolean result = false;
        try
        {
            float diffY = e2.getY() - e1.getY();
            float diffX = e2.getX() - e1.getX();
            if (Math.abs(diffX) > Math.abs(diffY))
            {
                if (Math.abs(diffX) >= SWIPE_THRESHOLD && Math.abs((int)velocityX) >= SWIPE_VELOCITY_THRESHOLD)
                {
                    if (diffX > 0)
                    {
                        if (listener != null)
                            listener.onSwipeRight();
                    }
                    else
                    {
                        if (listener != null)
                            listener.onSwipeLeft();
                    }
                }

                result = true;
            }
            else if (Math.abs(diffY) >= SWIPE_THRESHOLD && Math.abs((int)velocityY) >= SWIPE_VELOCITY_THRESHOLD)
            {
                if (diffY > 0)
                {
                    if (listener != null)
                        listener.onSwipeBottom();
                }
                else
                {
                    if (listener != null)
                        listener.onSwipeTop();
                }
            }
            result = true;

        }
        catch (Exception exception)
        {
            exception.printStackTrace();
        }
        return result;
    }

//    private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
//
//        private static final int SWIPE_THRESHOLD = 0;
//        private static final int SWIPE_VELOCITY_THRESHOLD = 0;
//    }
}
